package com.xhb.campusservices.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xhb.campusservices.common.lang.Result;
import com.xhb.campusservices.enums.OrderState;
import com.xhb.campusservices.enums.TaskState;
import com.xhb.campusservices.pojo.Orders;
import com.xhb.campusservices.pojo.Task;
import com.xhb.campusservices.pojo.orderDto.Complete;
import com.xhb.campusservices.pojo.orderDto.OrderManagement;
import com.xhb.campusservices.service.OrderMService;
import com.xhb.campusservices.service.OrderService;
import com.xhb.campusservices.service.TaskService;
import com.xhb.campusservices.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 订单管理
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    OrderMService orderMService;

    @Autowired
    TaskService taskService;

    @Autowired
    JWTUtils jwtUtils;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 我要接单
     *
     * @param orders
     * @param request
     * @return
     */
    @PostMapping("/receiveOrder")
    public Result receiveOrder(@Validated @RequestBody Orders orders, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(orders.getUserid()).equals(jwtUtils.getUserId(token))) {
            //获取该任务的信息
            Task byId = taskService.getById(orders.getTaskid());
            //如果该任务的userid和接单的userid一致则无法接任务
            if(byId.getUserid().equals(orders.getUserid())){
                return Result.fail(400, "此任务是自己发布的，无效接单!");
            }

            try {
                //设置发布时间为当前时间
                orders.setOrdertime(sdf.parse(sdf.format(new Date())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (orderService.save(orders)) {
                //UPDATE task SET taskstate = 2 WHERE id = 10;
                //接单成功，把Task的任务状态更改为  已被接单
                LambdaUpdateWrapper<Task> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(Task::getId, orders.getTaskid())
                        .set(Task::getTaskstate, TaskState.已被接单);
                taskService.update(updateWrapper);
                return Result.succ(200, "接单成功", orders);
            } else {
                return Result.fail("接单失败");
            }
        }

        return Result.fail(403, "没有接单权限!");

    }


    /**
     * 我的跑腿小哥(进行中)
     *
     * @param userId
     * @param request
     * @return
     */
    @GetMapping("/orders/{userId}")
    public Result orders(@PathVariable(name = "userId") Long userId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(userId).equals(jwtUtils.getUserId(token))) {
            List<OrderManagement> list = orderMService.orderManagementList(userId);
            if (list.size() == 0) {
                return Result.succ(200, "主人，还没有小哥接单哦~", null);
            }
            return Result.succ(list);
        }
        return Result.fail(403, "没有查看权限");
    }

    /**
     * 我的跑腿小哥(已完成)
     *
     * @param userId
     * @param request
     * @return
     */
    @GetMapping("/ordersComplete/{userId}")
    public Result ordersComplete(@PathVariable(name = "userId") Long userId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(userId).equals(jwtUtils.getUserId(token))) {
            List<OrderManagement> list = orderMService.completeL(userId);
            if (list.size() == 0) {
                return Result.succ(200, "主人，还没有任务完成哦~", null);
            }
            return Result.succ(list);
        }
        return Result.fail(403, "没有查看权限");
    }

    /**
     * 我的雇主(进行中)
     *
     * @param userId
     * @param request
     * @return
     */
    @GetMapping("/tasks/{userId}")
    public Result tasks(@PathVariable(name = "userId") Long userId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(userId).equals(jwtUtils.getUserId(token))) {
            List<OrderManagement> list = orderMService.orderMList(userId);
            if (list.size() == 0) {
                return Result.succ(200, "主人，还没有任务订单哦~", null);
            }
            return Result.succ(list);
        }
        return Result.fail(403, "没有查看权限");
    }

    /**
     * 确认完成订单
     *
     * @param orderC
     * @param request
     * @return
     */
    @PostMapping("/completeOrder")
    public Result completeOrder(@Validated @RequestBody Complete orderC, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(orderC.getUserId()).equals(jwtUtils.getUserId(token))) {
            LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Orders::getId, orderC.getId())
                    .set(Orders::getOrderstate, OrderState.已完成)
                    .set(Orders::getOrdertime, sdf.format(new Date()));
            if (orderService.update(updateWrapper)) {
                return Result.succ(200, "订单完成", null);
            }
            return Result.fail("订单修改失败");
        }
        return Result.fail(403, "没有修改权限");
    }

    /**
     * 我的雇主(已完成)
     *
     * @param userId
     * @param request
     * @return
     */
    @GetMapping("/complete/{userId}")
    public Result completeList(@PathVariable(name = "userId") Long userId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //查询账号是否一致
        if (String.valueOf(userId).equals(jwtUtils.getUserId(token))) {
            List<OrderManagement> list = orderMService.completeList(userId);
            if (list.size() == 0) {
                return Result.succ(200, "主人，还没有任务完成哦~", null);
            }
            return Result.succ(list);
        }
        return Result.fail(403, "没有查看权限");
    }
}
